package com.hn.vue.util;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;

import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.util.List;

/**
 * hanni
 * 2019/3/1 0001
 * 20:53
 */

/***
// * @param os 输出流
// * @param headers [用户名]
// * @param fields [name]
 *
 */
public class PoiUtil {

    public static void exportExecl(OutputStream os, List<String> headers, List<String> fields, List data) {

        try {
            Workbook wb = new HSSFWorkbook();
            Sheet sheet = wb.createSheet("用户信息");

//            CellStyle style = wb.createCellStyle();
//            style.setFillBackgroundColor(IndexedColors.BLUE.getIndex());
            //表头
            Row header = sheet.createRow(0);
            CellStyle cellStyle = wb.createCellStyle();

            cellStyle.setFillForegroundColor(IndexedColors.GREEN.getIndex());
            cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);

            for (int i = 0; i < headers.size(); i++) {
                Cell cell = header.createCell(i);
                cell.setCellValue(headers.get(i));
            }

            for (int i = 0; i < data.size(); i++) {
                Row row = sheet.createRow(i + 1);
                Object o = data.get(i);
                for (int j = 0; j < fields.size(); j++) {
                    Cell cell = row.createCell(j);
                    String s = fields.get(j);
                    Field field = o.getClass().getDeclaredField(s);
                    field.setAccessible(true);
                    Object fileValue = field.get(o);
                    if (fileValue != null)
                        cell.setCellValue(fileValue.toString());
                }
            }
            wb.write(os);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
